<template>
  <div>
    <el-form :inline="true">
      <el-form-item prop="name">
        <el-input v-model.trim="searchMaterial.name" placeholder="物料名称"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model.trim="searchMaterial.code" placeholder="物料编号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchMaterial.modelId" clearable placeholder="请选择型号">
          <el-option
            v-for="item in allModel"
            :key="item.id"
            :label="item.code"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchMaterial.brandId" clearable placeholder="请选择品牌">
          <el-option
            v-for="item in allBrand"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/物料导入模板.xlsx" download="物料导入模板.xlsx" style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载</el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 物料一览 -->
    <custom-table
      :columns="columns"
      :data="materialList"
      :taleLoadingFlag="taleLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 物料模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType ==='add'? '新增物料':'修改物料信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :rules="materialRules" :model="materialDto" label-width="80px" ref="materialForm">
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="materialDto.brandId" placeholder="请选择品牌" @change="brandChange">
            <el-option
              v-for="item in brandOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="modelId">
          <el-select v-model="materialDto.modelId" placeholder="请选择型号">
            <el-option
              v-for="item in modelOptions"
              :key="item.id"
              :label="item.code"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料编号" prop="code">
          <el-input v-model.trim="materialDto.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物料名称" prop="name">
          <el-input v-model.trim="materialDto.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户单价" prop="consumerPrice">
          <el-input type="number" v-model.number="materialDto.consumerPrice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="网点单价" prop="storePrice">
          <el-input type="number" v-model.number="materialDto.storePrice" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiMaterielReadExcel} from '@/api/excel/excelRead'
  import store from '@/store'
  import {apiGetModelList, apiGetBrandList} from '@/api/dictionary'
  import {
    apiGetMaterialList,
    apiGetMaterialById,
    apiDelMaterial,
    apiAddMaterial,
    apiUpdMaterial,
    apiExport
  } from '@/api/basic/info/material'
  import {baseInfo} from '@/utils/fetch'
  import {downloadExcel} from "../../../utils";

  export default {
    name: 'material',
    components: {CustomTable},
    data () {
      var checkNum = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('价格不能为空'))
        } else if (value < 1 || value > 10000000000000000) {
          callback(new Error('数字大小应在1到10000000000000000之间'))
        } else {
          callback()
        }
      }
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        dialogVisible: false,                       // 模态框相关数据
        hideTable: false,
        uploadVisible: false,
        wrongDataList: [],
        dialogType: '',
        filePath: '',
        allModel: [],
        allBrand: [],
        searchMaterial: {
          name: '',
          code: '',
          modelId: '',
          brandId: ''
        },
        listQuery: {
          code: undefined,
          name: undefined,
          model: undefined,
          brand: undefined
        },
        materialDto: {
          id: undefined,
          brandId: undefined,
          modelId: undefined,
          code: undefined,
          name: undefined,
          consumerPrice: undefined,
          storePrice: undefined
        },
        brandOptions: this.getBrandList(),  // 品牌类型
        modelOptions: [],                     // 型号类型
        materialRules: {
          brandId: [{type: 'number', required: true, message: '请选择品牌', trigger: 'change'}],
          modelId: [{type: 'number', required: true, message: '请选择型号', trigger: 'change'}],
          code: [{required: true, message: '请输入物料编号', trigger: 'blur'},
            {max: 10, message: '长度不得超过10字符', trigger: 'blur'}],
          name: [{required: true, message: '请输入物料名称', trigger: 'blur'},
            {max: 50, message: '长度不得超过50字符', trigger: 'blur'}],
          consumerPrice: [{type: 'number', required: true, message: '请输入用户单价', trigger: 'blur'},
            {type: 'number', message: '用户单价必须是数字', trigger: 'blur'},
            {validator: checkNum, trigger: 'blur'}],
          storePrice: [{type: 'number', required: true, message: '请输入网点单价', trigger: 'blur'},
            {type: 'number', message: '网点单价必须是数字', trigger: 'blur'},
            {validator: checkNum, trigger: 'blur'}]
        },
        taleLoadingFlag: false, // 物料一览相关数据
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '物料编号', name: 'code', align: 'center'},
          {label: '物料名称', name: 'name', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: '网点单价(元)', name: 'storePrice', align: 'center'},
          {label: '用户单价(元)', name: 'consumerPrice', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '物料编号', name: 'code', align: 'center'},
          {label: '物料名称', name: 'name', align: 'center'},
          {label: '品牌', name: 'brand', width: '200', align: 'center'},
          {label: '型号', name: 'model', width: '200', align: 'center'},
          {label: '网点单价', name: 'storePrice', width: '200', align: 'center'},
          {label: '用户单价', name: 'consumerPrice', width: '200', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        materialList: [],
        pagination: this.getData(this.getMaterialList)
      }
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getMaterialList(listQuery)
      this.getAllModel()
      this.getAllBrand()
    },
    methods: {
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      excelExport () {
        let paramsPost = {
          modelId: this.searchMaterial.modelId,
          brandId: this.searchMaterial.brandId,
          code: this.searchMaterial.code,
          name: this.searchMaterial.name
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后物料信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功！'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      excelRead (filePath) {
        apiMaterielReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getMaterialList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      getMaterialList (listQuery) {
        this.taleLoadingFlag = true
        if (listQuery.name === undefined) {
          listQuery.name = this.searchMaterial.name
        }
        if (listQuery.model === undefined) {
          listQuery.model = this.searchMaterial.modelId
        }
        if (listQuery.brand === undefined) {
          listQuery.brand = this.searchMaterial.brandId
        }
        if (listQuery.code === undefined) {
          listQuery.code = this.searchMaterial.code
        }
        apiGetMaterialList(listQuery).then(response => {
          this.materialList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.taleLoadingFlag = false
        }).catch(() => {
          this.taleLoadingFlag = false
        })
      },
      getAllModel () {
        apiGetModelList().then(response => {
          this.allModel = response.data
        })
      },
      getAllBrand () {
        apiGetBrandList().then(response => {
          this.allBrand = response.data
        })
      },
      handleAdd () {
        this.dialogType = 'add'
        this.dialogVisible = true
        if (this.$refs['materialForm']) {
          this.materialDto = {
            id: undefined,
            brandId: undefined,
            modelId: undefined,
            code: undefined,
            name: undefined,
            consumerPrice: undefined,
            storePrice: undefined
          }
          this.$refs['materialForm'].resetFields()
        }
      },
      handleEdit (row) {
        this.materialDto.id = row.id
        var that = this
        apiGetMaterialById(row.id).then(response => {
          let data = response.data
          that.materialDto = {
            id: row.id,
            brandId: data.brandId,
            modelId: undefined,
            code: data.code,
            name: data.name,
            consumerPrice: data.consumerPrice,
            storePrice: data.storePrice
          }

          var search = this.getModelList({brandId: data.brandId})
          var res = search.then(function (value) {
            that.modelOptions = value
            value.forEach(function (item) {
              if (item.id == data.modelId) {
                that.materialDto.modelId = data.modelId;
              }
            });
          }, function (value) {

          });

          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },

      brandChange (val) {
        var that = this;
        var search = this.getModelList({brandId: val})
        var flag = 0;
        var res = search.then(function (value) {
          that.modelOptions = value
          if (that.materialDto.id == null || that.materialDto.id == undefined) {
            that.materialDto.modelId = undefined
          } else {
            var oldModleId = that.materialDto.modelId;
            that.materialDto.modelId = undefined
            value.forEach(function (item) {
              if (item.id == oldModleId) {
                that.materialDto.modelId = oldModleId;
              }
            });
          }
        }, function (value) {

        });
      },
      handleDel (row) {
        this.$confirm('确定删除该物料档案?', '删除物料', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelMaterial(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getMaterialList(this.listQuery)
          })
        }).catch(() => {
        })
      },
      submit () {
        this.$refs.materialForm.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit () {
        apiAddMaterial(this.materialDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.cancel()
          this.getMaterialList(this.listQuery)
        })
      },
      updSubmit () {
        apiUpdMaterial(this.materialDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.cancel()
          this.getMaterialList(this.listQuery)
        })
      },
      cancel () {
        this.dialogVisible = false
        this.$refs['materialForm'].resetFields()
      },
      searchData () {
        this.listQuery.code = this.searchMaterial.code
        this.listQuery.name = this.searchMaterial.name
        this.listQuery.brand = this.searchMaterial.brandId
        this.listQuery.model = this.searchMaterial.modelId
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getMaterialList(this.listQuery)
      }
    }
  }
</script>
